package com.huanwei.read;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.huanwei.cc.bean.XinWen;
import com.huanwei.cc.http.AsyncManaer;
import com.huanwei.cc.http.XianTaiWangAPI;
import com.huanwei.read.adapter.Meir_Adapter;
import com.huanwei.cc.ui.DefineBAGRefreshWithLoadView;

import com.wang.avi.AVLoadingIndicatorView;
import com.huanwei.cc.base.MyApplication;
import com.huanwei.cc.R;
import com.huanwei.cc.bean.DYD_Beam;
import com.huanwei.cc.utils.JSONUtils;
import com.huanwei.cc.utils.LogUtil;
import com.huanwei.cc.utils.NetUtil;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;


/**
 * 每日一文
 */
public class MeiRi_Fragment extends Fragment implements BGARefreshLayout.BGARefreshLayoutDelegate {

    @BindView(R.id.lv_lv)
    ListView mListView;
    @BindView(R.id.layout_no)
    RelativeLayout layoutNo;
    @BindView(R.id.loading_layout)
    AVLoadingIndicatorView loadingLayout;
    @BindView(R.id.layout_no_w)
    RelativeLayout layoutNoW;
    private int mPage = 1;
    View view;

    boolean ispaper;
    boolean isjiazai = true;
    Meir_Adapter adapters;
    public static final int DADE_NO_W = 1000;
    public static final int DADE_NO_SJ = 1001;
    public static final int DADE_NO_SXWC = 1002;
    public static final int DADE_NO_SLWC = 1003;
    private BGARefreshLayout mRefreshLayout;
    //自定义的刷新加载view
    DefineBAGRefreshWithLoadView defineloadview;
    List<XinWen.ResultBean.DataBean> result;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            ispaper = true;
            view = View.inflate(getActivity(), R.layout.fragment_mr, null);
            mRefreshLayout = (BGARefreshLayout) view.findViewById(R.id.bga_refresh);
            ButterKnife.bind(this, view);
            initview();

            Firstrequest();
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        return view;
    }


    public AdapterView.OnItemClickListener mbankcardListItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (NetUtil.isNetworkAvailable(getActivity())) {
                // 获得数据 通过页数

                Intent intent = new Intent(getActivity(), web_Activity.class);
                XinWen.ResultBean.DataBean cc = (XinWen.ResultBean.DataBean) adapters.getItem(position);
                Log.e("position", "111" + position);
                intent.putExtra("id", cc.getUrl());
                getActivity().startActivity(intent);
            } else {
                Toast.makeText(getActivity(), "请检查网络连接", Toast.LENGTH_SHORT).show();
            }


        }
    };


    private void initview() {
        adapters = new Meir_Adapter();
        mListView.setAdapter(adapters);
        mListView.setOnItemClickListener(mbankcardListItemClickListener);
        layoutNoW.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutNoW.setVisibility(View.INVISIBLE);
                Firstrequest();
            }
        });
        mRefreshLayout.setDelegate(this);
        defineloadview = new DefineBAGRefreshWithLoadView(getActivity(), false, false);
        mRefreshLayout.setRefreshViewHolder(defineloadview);


    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        Log.e("11111 ", "111111下拉刷新");
        // 第一页
        mPage = 1;
        // 请求数据
        requestData();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        Log.e("11111222 ", "11111122上拉加载");
        defineloadview.showLoadingMoreImg();
        defineloadview.updateLoadingMoreText("加载中");
        mPage++;
        // 请求数据
        requestData();
        return true;
    }

    //加载网络数据
    private void Firstrequest() {
//        LogUtil.log("加载网络数据");
        layoutNo.setVisibility(View.INVISIBLE);
        mRefreshLayout.setVisibility(View.INVISIBLE);
        loadingLayout.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (NetUtil.isNetworkAvailable(MyApplication.getInstance())) {
                    getData(mPage);
                    //有网
                } else {
                    //没网
                    loadingLayout.setVisibility(View.INVISIBLE);
                    layoutNoW.setVisibility(View.VISIBLE);

                }
            }
        }, 0);


    }

    public void getData(int page) {


        XianTaiWangAPI.getname(getActivity(), String.valueOf(page), "10", new AsyncManaer.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                if (!TextUtils.isEmpty(st)) {
                    Log.e("121212", "121212" + st);

                    XinWen no_token_message = JSONUtils.parseJSONArray(st, XinWen.class);


                    result = no_token_message.getResult().getData();

                    //有数据
                    if (mPage == 1) {
                        if (result != null && result.size() > 0) {
                            Log.e("111", "111" + "有数据" + mPage);
                            adapters.clear();
                            adapters.addItem(result);
                            mHandler.sendEmptyMessage(DADE_NO_SXWC);
                            loadingLayout.setVisibility(View.INVISIBLE);
                            mRefreshLayout.setVisibility(View.VISIBLE);

                        } else {
                            Log.e("111", "111" + "无数据" + mPage);

                            loadingLayout.setVisibility(View.INVISIBLE);
                            layoutNo.setVisibility(View.VISIBLE);
                            mRefreshLayout.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if (result != null && result.size() > 0) {
                            mHandler.sendEmptyMessage(DADE_NO_SLWC);
                            adapters.addItem(result);
                            Log.e("111", "111" + "上拉加载有数据" + mPage);
                        } else {
                            mPage--;
                            Log.e("111", "111" + "上拉加载空" + mPage);
                            mHandler.sendEmptyMessage(DADE_NO_SJ);
                        }


                    }


                }
            }

            @Override
            public void onFalia(int code, String errst) {
                Log.e("111", errst);
            }
        });

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DADE_NO_W:
                    mRefreshLayout.endRefreshing();
                    mRefreshLayout.endLoadingMore();
                    break;
                case DADE_NO_SJ:
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            defineloadview.hideLoadingMoreImg();
                            defineloadview.updateLoadingMoreText("没有更多数据了");
                            mRefreshLayout.endLoadingMore();

                        }
                    }, 1000);
                    break;
                case DADE_NO_SXWC:

                    mRefreshLayout.endRefreshing();

                    break;
                case DADE_NO_SLWC:
                    mRefreshLayout.endLoadingMore();

                    break;
                default:
                    break;
            }

        }

    };


    private void requestData() {
        // 是否有网
        if (NetUtil.isNetworkAvailable(getActivity())) {
            // 获得数据 通过页数
            LogUtil.log("有网");
            getData(mPage);
        } else {
            // 没网 发消息
            mPage--;
            mHandler.sendEmptyMessage(DADE_NO_W);
        }
    }


}

